$(document).ready(function(){
    
    // Handle the gui update of the privacy menu.
	$('.setting').click(function(){
		
		// Clear-up old one.
		$('.activeSetting').removeClass('activeSetting');
		$(this).addClass('activeSetting');
	});
	
    // Save privacy settings.
	$('#saveSetting').click(function(){
		var active = $('.activeSetting');
		var isPublic = 0;
		
		if(active.attr('id') === 'settingsPublic'){
			isPublic = 1;
		}
		
        // Make the ajax call.
        $.ajax({
            data: {
                'isPublic': isPublic
            },
            url: 'ajaj/updatePrivacySettings',
            type: 'post',
            dataType: 'json',
            success: function(){
                
                // Hide the mask and window.
                $('#mask, .window').hide();
                
                // Show a notification to the user.
                var msg = 'openbaar.';
                
                if(!isPublic){
                    msg = 'priv&eacute.';
                }
                
                showNot('Uw profiel is nu ' + msg);
            }
        });
	});

    // Show the privacy settings menu.
	$('#privacySettingsLink').click(function(e) {
        
        // Get the settings first.
        $.ajax({
            data: {},
            url: 'ajaj/getUserPrivacySettings',
            type: 'get',
            dataType: 'json',
            success: function(result){
                $('.activeSetting').removeClass('activeSetting');
                
                if(result.isPublic === '0'){
                    $('#settingsPrivate').addClass('activeSetting');
                } else {
                    $('#settingsPublic').addClass('activeSetting');
                }
                
                // Hide the dropdown.
                $('#profileMenu').hide();

                e.preventDefault();
                var id = '#privacySettings';
                var maskHeight = $(document).height();
                var maskWidth = $(window).width();

                $('#mask').css({
                    'width': maskWidth,
                    'height': maskHeight,
                    'opacity': 0.3
                }).show();

                $(id).css('top',  $(window).height() / 2-$(id).height() / 2);
                $(id).css('left', $(window).width() / 2-$(id).width() / 2);
                $(id).show();
            }
        });
	});
	
	$('#groupsLink').click(function(e) {
		$('#profileMenu').hide();
	
		e.preventDefault();
		var id = '#groups';
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		$('#mask').css({
			'width': maskWidth,
			'height': maskHeight,
			'opacity': 0.3
		}).show();
		
		$(id).css('top',  $(window).height() / 2-$(id).height() / 2);
		$(id).css('left', $(window).width() / 2-$(id).width() / 2);
		$(id).show();
		
		return false;
	});

	// Logo redirects to the homepage.
	$('#logo').click(function(){
		window.location = url + 'index/home';
	});
	
	var elWidth = 110;
	
	if($('#profile').outerWidth() > 110){
		elWidth = $('#profile').outerWidth();
	}

	// If the image was in cache.
	$('#profileMenu li').width(elWidth);
	
	// The 20 fixes the box shadow, because of the 10px padding on the children.
	$('#profileMenu').width(elWidth + 20);

	// Position the profile menu.
	$('#actualProfileIcon').load(function() { 
		$('#profileMenu li').width(elWidth);
		
		// The 20 fixes the box shadow, because of the 10px padding on the children.
		$('#profileMenu').width(elWidth + 20);
	});
	
	// Position the notfications dropdown menu.
	$('#notificationsMenu').css({
		'margin-left': $('#logo').width() + 5
	});
	
	// Hide the menu's
	$('#profileMenu').hide();
	$('#notificationsMenu').hide();
	
	// $('#box1').animate({boxShadow: '0 0 30px #44f'});
	$('#notifications').click(function(e){
		if($('#notificationsMenu').is(':visible')){
			$('#notificationsMenu').hide();
		} else {
			$('#notificationsMenu').show();
		}
		
		// Prevent the menu from dissapearing while clicking in document.
		e.stopPropagation();
	});
	
	// Prevent the menu from dissapearing while clicking in document.
	$('#notificationsMenu').click(function(e){
		e.stopPropagation();
	});
	
	// Prevent the menu from dissapearing while clicking in document.
	$('#profileMenu').click(function(e){
		e.stopPropagation();
	});
	
	// Make the menu dissapear while clicking anywhere else than the menu itself.
	$(document).click(function() {
	    $('#profileMenu').hide();
	    $('#notificationsMenu').hide();
	    $('#createActivityLocationResults').hide();
	});
	
	// Profile menu
	$('#profile').click(function(e){
		if($('#profileMenu').is(':visible')){
			$('#profileMenu').hide();
		} else {
			$('#profileMenu').show();
		}
		
		// Prevent the menu from dissapearing while clicking in document.
		e.stopPropagation();
	});
	
	var defaultSearchInputWidth = 200;
	var animatedSearchInputWidth = 300;
	var searchResultListItemMargin = 50;
	
	$('#searchInput').width(defaultSearchInputWidth);
	$('#searchResults ul li').width(defaultSearchInputWidth + searchResultListItemMargin);
	
	function clickSearchResult(item){
		item = $(item);
		
		var url = 'profile/';
		var param = $(item).attr('id');
		
		if(item.hasClass('friend')){
			url += 'user';
		} else if(item.hasClass('city')){
			url += 'city';
		} else if(item.hasClass('company')){
			url += 'location';
		} 
		
        window.location = url + '/' + param;
	}
    
    $('#extendedSearch').click(function(){
        doExtendedSearch();
    });
	
	// Autocomplete searching.
	var input = $('#searchInput');
	var cache = new Cache();
	var timeout;
	var resultCount = 0;
	var selectedDropdownItem = null;
	var minChars = 2;
	var searchDelay = 400;
	var max = 15;
    var inputLocked = false;
	
    var dropdown = $("<ul>")
    .attr('id', 'actualSearchResults')
    .appendTo('#searchResults')
    .mouseover(function(event){
		selectDropdownItem($(event.target).closest("li"))
	})
	.hide();
    
	function animateSearchInput(newWidth){
        if(inputLocked === false){
            var searchInputAnimationSpeed = 200;
            var width = $('#searchInputContainer').outerWidth();
            $('#searchResults li').css({'width': width - 20});

            $('#searchInput').animate({
                width: newWidth + 'px'
            }, searchInputAnimationSpeed, function(){
                $('#searchResults ul li').animate({
                    width: ($('#searchInput').width() + searchResultListItemMargin) + 'px'
                }, searchInputAnimationSpeed);
            });
        }
	}
    
    function friendFormatter(item){
    	output = '<li class="friend" id="' + item['friendUserId'] + '">';
    		output += '<div class="profilePicture"><img src="https://graph.facebook.com/' + item['friendUserId'] + '/picture" alt="' + ucwords(item['name']) + '" /></div>';
    		output += '<table class="content"><tbody>';
    			output += '<tr><td class="title">' + ucwords(item['name']) + '</td></tr>';
    			output += '<tr><td>Facebook vriend</td></tr>';
    			if(item['onHikle']){
    				output += '<tr><td class="secondTitle">Maakt gebruik van Hikle.</td></tr>';
    			}
    		output += '</tbody></table>';
    		output += '<div class="clear"></div>';
    	output += '</li>';
    	
    	return output;
    }
    
    function cityFormatter(item){
       	output = '<li class="city" id="' + item['id'] + '">';
    		// $output += '<div class="profilePicture"><img src="https://graph.facebook.com/' + item['friendUserId'] + '/picture" alt="' + ucwords(item['name']) + '" /></div>';
    		output += '<table class="content"><tbody>';
    			output += '<tr><td class="title">' + ucwords(item['name']) + '</td></tr>';
    			output += '<tr><td>Plaats</td></tr>';
    		output += '</tbody></table>';
    		output += '<div class="rightContent"><div class="flag ' + item['country'] + '"></div></div>';
    		output += '<div class="clear"></div>';
    	output += '</li>';
    	
    	return output;
    }
    
    function companyFormatter(item){
       	output = '<li class="company" id="' + item['id'] + '">';
    		// $output += '<div class="profilePicture"><img src="https://graph.facebook.com/' + item['friendUserId'] + '/picture" alt="' + ucwords(item['name']) + '" /></div>';
    		output += '<table class="content"><tbody>';
    			output += '<tr><td class="title">' + ucwords(item['name']) + '</td></tr>';
    			output += '<tr><td>' + ucwords(item['branch']) + '</td></tr>';
    			output += '<tr><td class="secondTitle">' + ucwords(item['city']) + '</td></tr>';
    		output += '</tbody></table>';
    		// output += '<div class="rightContent"><div class="flag ' + item['country'] + '"></div></div>';
    		output += '<div class="clear"></div>';
    	output += '</li>';
    	
    	return output;
    }
    
    function doExtendedSearch(){
        if(input.val() === input.attr('placeholder') || input.val().length < 4){
            return false;
        }
        
    	// window.location = 'index/search/' + input.val();
        
        $('#middleColumn div').hide();
        $('#leftColumn').animate({width: 'hide'}, 100, function(){
            $('#middleColumn').animate({
                'width': '768px'
            }, 400);
        });

        lockInput();
        
        // Hide dropdown.
        hideDropdown();
        
        var eSearchLoader = '<div class="loader" id="eSearchLoader"></div>';
        eSearchLoader = $(eSearchLoader);
        eSearchLoader.appendTo('#middleColumn');
        eSearchLoader.show();
        var keyword = input.val();
        
        $('#searchTitle').remove();
        $('<div id="searchTop"></div>').appendTo('#middleColumn');
        
        var searchTitle = '<div id="searchTitle">Uitgebreide zoekresultaten voor <font class="blue">"' + keyword + '"</font></div>';
        searchTitle = $(searchTitle);
        searchTitle.appendTo('#searchTop');
        
         $('<div class="right"><div class="flag nl"></div></div>').appendTo('#searchTop');
        $('<div class="clear"></div>').appendTo('#searchTop');
       
        
        $('#extendedSearchResults').remove();
        var searchResultContainer = '<div id="extendedSearchResults"></div>';
        searchResultContainer = $(searchResultContainer);
        searchResultContainer.appendTo('#middleColumn');
        
        $.ajax({
            data: {
                'keyword': keyword
            },
            url: 'ajaj/extendedSearch',
            type: 'post',
            dataType: 'json',
            success: function(results){
                if(results){
                    var total = results.cities.length + results.companies.length + results.users.length;
                    
                    if(total === 0){
                        var li = '<li id="eSearchNoResults">';
                            li += 'Geen zoek resultaten.';
                        li += '</li>';
                        li = $(li);
                        li.appendTo('#extendedSearchResults');
                        eSearchLoader.remove();
                        return;
                    }
                    
                    $.each(results.cities, function(i, v){
                        var li = '<li class="eSearchResult city" id="' + v.id + '">';
                            // li += '<div class="picture"></div>';
                            li += '<table class="content">';
                                li += '<tr><td class="title">' + ucwords(v.name) + '</td></tr>';
                                li += '<tr><td class="subtitle">Plaats</td></tr>';
                                li += '<tr><td class="subsubtitle"></td></tr>';
                            li += '</table>';
                            li += '<div class="clear"></div>';
                        li += '</li>';
                        li = $(li);
                        li.appendTo('#extendedSearchResults');
                    });
                    
                    $.each(results.companies, function(i, v){
                        var li = '<li class="eSearchResult company" id="' + v.id + '">';
                            // li += '<div class="picture"></div>';
                            li += '<table class="content">';
                                li += '<tr><td class="title">' + ucwords(v.name) + '</td></tr>';
                                li += '<tr><td class="subtitle">' + ucwords(v.city) + '</td></tr>';
                                li += '<tr><td class="subsubtitle">' + ucwords(v.branch) + '</td></tr>';
                            li += '</table>';
                            li += '<div class="clear"></div>';
                        li += '</li>';
                        li = $(li);
                        li.appendTo('#extendedSearchResults');
                    });
                    
                    $.each(results.users, function(i, v){
                        var li = '<li class="eSearchResult user" id="' + v.id + '">';
                            li += '<div class="picture"><img src="https://graph.facebook.com/' + v.id + '/picture" alt="' + ucwords(v.name) + '" /></div>';
                            li += '<table class="content">';
                                li += '<tr><td class="title">' + ucwords(v.name) + '</td></tr>';
                                li += '<tr><td class="subtitle">Gebruiker van Hikle</td></tr>';
                                li += '<tr><td class="subsubtitle"></td></tr>';
                            li += '</table>';
                            li += '<div class="clear"></div>';
                        li += '</li>';
                        li = $(li);
                        li.appendTo('#extendedSearchResults');
                    });
                    
                    eSearchLoader.remove();
                    
                    $('.eSearchResult').click(function(){
                        var action = '';
                        
                        if($(this).hasClass('city')){
                            action = 'city';
                        } else if($(this).hasClass('user')){
                            action = 'user';
                        } else if($(this).hasClass('company')){
                            action = 'company';
                        }
                        
                        window.location = url + 'profile/' + action + '/' + $(this).attr('id');
                    });
                }
            }
        });
    }
    
    function lockInput(){
		input.animate({
			width: '300px'
		}, 500);
        
        inputLocked = true;
        input.blur();
    }
    
    function unlockInput(){
        // do something?
    }
	
	input.focus(function(){
		animateSearchInput(animatedSearchInputWidth);
		showDropdown();
	})
	.blur(function(){
		setTimeout(function(){
			animateSearchInput(defaultSearchInputWidth);
			hideDropdown();
		}, 100);
	})
	.keydown(function(event){
		switch(event.keyCode){
			case keys.escape:
				hideDropdown();
				break;
            case keys.left:
            case keys.right:
            case keys.up:
            case keys.down:
	            var dropdownItem = null;
	
	            if(event.keyCode === keys.down || event.keyCode === keys.right){
	                dropdownItem = $(selectedDropdownItem).next();
	            } else {
	                dropdownItem = $(selectedDropdownItem).prev();
	            }
	
	            if(dropdownItem.length) {
	                selectDropdownItem(dropdownItem);
	            }
	            return false;
            case keys.enter:
            	doExtendedSearch();
                return false;
			default:
				if(String.fromCharCode(event.which)){
					setTimeout(function(){
						doSearch(input);
					}, 5);
				}
				break;
		}
	});
	
	function doSearch(){
		var query = input.val().toLowerCase();
		
		if(query && !inputLocked){
            if(query.length >= minChars) {
                clearTimeout(timeout);
                timeout = setTimeout(function(){
                	runSearch(query);
                }, searchDelay);
            } else {
                hideDropdown();
            }
		}
	}
	
    function selectDropdownItem(item){
        if(item) {
            if(selectedDropdownItem){
                deselectDropdownItem($(selectedDropdownItem));
            }

            item.addClass('hover');
            selectedDropdownItem = item.get(0);
        }
    }
    
    function deselectDropdownItem(item){
        item.removeClass('hover');
        selectedDropdownItem = null;
    }
    
	function showDropdown(){
        if(inputLocked === false){
            dropdown.show();
            $('#searchResults').show();
        }
	}
	
	function hideDropdown(){
		selectedDropdownItem = null;
		dropdown.hide();
		$('#searchResults').hide();
	}
    
    function runSearch(query) {
    	$('#searchLoader').show();
    	var cachedResults = cache.get(query, undefined);
    	
    	if(cachedResults){
    		populateDropdown(query, cachedResults);
    	} else {
            $.ajax({
                data: {
                    'keyword':query
                },
                url: 'ajaj/search',
                type: 'post',
                dataType: 'json',
                success: function(results){
                    cache.add(query, results);
                    
                    if(input.val().toLowerCase() === query){
                        populateDropdown(query, results);
                    }
                }
            });
    	}
    }
    
    function populateDropdown(query, results){
    	var resultCount = 0;
    	var totalResultCount = 0;
    	dropdown.empty();
    	
    	if(results.friends){
    		totalResultCount += results.friends.length;
    	}
    	
    	if(results.cache){
    		totalResultCount += results.cache.length;
    	}

		// Friends
		if(results.friends !== undefined){
			$.each(results.friends, function(index, value){
				if(resultCount <= max){
					var li = friendFormatter(value);
					li = $(li);
		    		
					// select the first li!
					if(resultCount === 0){
						selectDropdownItem(li);
						li.addClass('first');
					}
		    		
		    		resultCount++;
		    		
		    		if(resultCount === totalResultCount){
		    			li.addClass('last');
		    		}
		    		
		    		li.appendTo(dropdown);
		    		li.click(function(){
		    			clickSearchResult(li);
		    		});
	    		}
			});
		}
		
		// Cities
		if(results.cache.length){
			$.each(results.cache, function(index, value){
				if(resultCount <= max){
					var li;
                    
					if(value.objectType === '3'){
						li = cityFormatter(value);
					} else if(value.objectType === '1'){
						li = companyFormatter(value);
					}
					
					li = $(li);
					
					// select the first li!
					if(resultCount === 0){
						selectDropdownItem(li);
						li.addClass('first');
					}
					
					resultCount++;
					
					if(resultCount === totalResultCount){
						li.addClass('last');
					}
					
					li.appendTo(dropdown);
		    		li.click(function(){
		    			clickSearchResult(li);
		    		});
				}
			});
		}
		
    	if(resultCount > 0){
    		showDropdown();
    	} else {
    		selectedDropdownItem = null;
    	}
    	
    	$('#searchResults ul li').width($('#searchInput').width() + 50);
    	$('#searchLoader').hide();
    }
    
    loadNotifications();
    
    function displayNotCount(amount){
        var notCount = '<span id="notCount">' + amount + '</span>';
        notCount = $(notCount);
        notCount.appendTo('#notifications');
        
        // Resize.
        var width = 0;

        if($('#notifications span').length){
            if($('#notifications span').html().length === 1){
                width = 30;
            } else if($('#notifications span').html().length === 2){
                width = 35;
            } else if($('#notifications span').html().length === 3){
                width = 40;
            } else if($('#notifications span').html().length === 4){
                width = 50;
            }
        }
        
        $('#notifications').width(width + 'px');
    }
    
    var notCount = 0;
    
    function loadNotifications(){
        $.ajax({
            url: 'ajaj/readNotifications',
            type: 'post',
            dataType: 'json',
            success: function(results){
                if(results && results.length){
                    notCount = results.length;
                    displayNotCount(notCount);
                    
                    $.each(results, function(i, a){
                        li = addNotification(a);
                        li = $(li);
                        li.appendTo('#notificationsMenu');
                        
                        // Posted x minutes ago etc.
                        var t = a.createdOn.split(/[- :]/);
                        var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);

                        $('#timeago_not_' + a.notId).attr("title", iso8601(d));
                    });
                    
                    $('#notificationsMenu li .sprite').click(function(){
                        if($(this).hasClass('remove')){
                            var answer = confirm('Weet u zeker dat u niet akkoord gaat? Zo ja wordt de uitnodiging permanent verwijdert.');
                            
                            if(answer){
                                decideNot($(this).parent().attr('id'), 0);
                            }
                        } else if($(this).hasClass('check')){
                            decideNot($(this).parent().attr('id'), 1);
                        }
                    });
                }
            }
        });
    }
    
    function addNotification(a){
        var li = '<li id="anot_' + a.notId + '">';
            li += '<div class="profilePicture">';
                li += '<img src="https://graph.facebook.com/' + a.createdBy + '/picture" alt="' + ucwords(a.name) + '">';
            li += '</div>';
            li += '<table class="notificationContent">';
            li += '<tbody>';
                li += '<tr><td class="title">' + ucwords(a.name) + '</td></tr>';
                li += '<tr>';
                    var identifier = 'hij';
                
                    if(a.sex === 'female'){
                        identifier = 'zij';
                    }
                
                    li += '<td class="text">Heeft aangegeven dat ' + identifier + ' met jou op ' + a.date + ' om ' + a.time.substr(0, 5);
                    li += ' naar ';
                    
                    if(a.destType === '1'){
                        li += '<a href="profile/company/' + a.obj['id'] + '">' + ucwords(a.obj['name']) + '</a>';
                    } else if(a.destType === '2'){
                        li += '<a href="profile/user/' + a.obj['id'] + '">' + ucwords(a.obj['name']) + '</a>';
                    } else if(a.destType === '3'){
                        li += '<a href="profile/city/' + a.obj['id'] + '">' + ucwords(a.obj['name']) + '</a>';
                    }
                    
                    li += ' gaat. Klopt dit?';
                    li += '<td class="answer">';
                        li += '<div class="answer_button" id="' + a.notId + '">';
                            li += '<div class="sprite remove"></div>';
                            li += '<div class="sprite check"></div>';
                        li += '</div>';
                    li += '</td>';
                li += '</tr>';
                li += '<tr>';
                    li += '<td><abbr class="datetime timeago" id="timeago_not_' + a.notId + '"></td>';
                li += '</tr>';
            li += '</tbody>';
            li += '</table>';
        li += '</li>';
        return li;
    }
    
    function decideNot(id, bool){
        $.ajax({
            url: 'ajaj/updateNotification',
            data: {
                'id': id,
                'decision': bool
            },
            type: 'post',
            dataType: 'json',
            success: function(result){
                $('#anot_' + id).remove();
                notCount--;
                
                if(notCount > 0){
                    displayNotCount(notCount);
                } else {
                    $('#notCount').remove();
                }
            }
        });
    }
});